# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exporters import JsonItemExporter
from twisted.internet import defer, reactor


# from rule_spider.models.scrapy_redis_sentinel.bloomfilter import BloomFilter



class JsonExporterPipeline(object):
    def __init__(self):
        pass

    def open_spider(self, spider):
        self.file = open('data_{}.json'.format(spider.name), 'wb')  # 必须二进制写入
        self.exporter = JsonItemExporter(self.file, encoding='utf-8', ensure_ascii=False)
        # 开始写入
        self.exporter.start_exporting()

    def process_item(self, item, spider):
        item_name = item.__str__()
        if item_name == 'ShopBaseyItem':
            json_data = item.form_data()
            self.exporter.export_item(json_data)
        else:
            self.exporter.export_item(item)
        return item

    def close_spider(self, spider):
        # 完成写入
        self.exporter.finish_exporting()
        self.file.close()
        pass

